package cc.owoo.godpen.network;

import cc.owoo.godpen.thread.Threads;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by nimensei
 * 2022-03-31 上午 01:58
 **/
public class SocketUtil {
    /**
     * 启动一个服务端口，并监听
     *
     * @param port     需要监听的端口
     * @param onAccept 监听回调函数
     * @return ServerSocket对象
     */
    public static ServerSocket server(int port, OnAccept onAccept) throws IOException {
        return server(port, onAccept, null);
    }

    /**
     * 启动一个服务端口，并监听
     *
     * @param port     需要监听的端口
     * @param onAccept 监听回调函数
     * @param onClose  服务器关闭回调函数
     * @return ServerSocket对象
     */
    public static ServerSocket server(int port, OnAccept onAccept, Runnable onClose) throws IOException {
        if (onAccept == null)
            throw new IllegalArgumentException("监听对象不能为空");
        ServerSocket serverSocket = new ServerSocket(port);
        new Thread(() -> {
            while (true) {
                Socket socket = null;
                try {
                    socket = serverSocket.accept();
                } catch (IOException ignored) {
                }
                if (socket == null)
                    break;
                Socket finalSocket = socket;
                Threads.run(() -> onAccept.accept(finalSocket));
            }
            try {
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (onClose != null)
                onClose.run();
        }).start();
        return serverSocket;
    }

    public interface OnAccept {
        void accept(Socket socket);
    }
}
